#include <iostream>
#include <cstdlib>
#include <cstring>

typedef struct student
{
    int id;
    char name[50];
    float chinese;
    float math;
    float english;
    float sum;
}student;

int PrintStudents(student stu[], int n);
int ReadStuInfoFromFile(char *name, student **stu);
int NoPass(student stu[], int n, student **noPassStudent, int *m);
int Pass(student stu[], int n, student **PassStudent, int *m);
int SortStudents(student stu[], int n);
int SearchStudent(student stu[], int n, int id,int *rank, student *rstu);

int ReadStuInfoFromFile(char* name, student** stu)
{
    FILE* f;
    int n;
    if((f = fopen(name,"r"))==NULL)
        return 0;
    if(fread(&n, sizeof(int), 1, f)!=1)
        return 0;
    *stu = new student[sizeof(student)*n];
    if (fread(*stu, sizeof(student), n, f) != n)
        return 0;
    for (int i = 0; i < n; i++)
        (*stu+i)->sum = (*stu + i)->chinese + (*stu + i)->math + (*stu + i)->english;

    return n;
}



int NoPass(student stu[], int n, student** noPassStudent, int* m)
{
    if (n <= 0||stu==NULL)
    {
        return -1;
    }
    *m = 0;
    int *a = new int[n*sizeof(int)];
    for (int i = 0;i < n;i++)
    {
        if (stu[i].sum < 180)
        {
            a[*m] = i;
            *m += 1;
        }
    }

    *noPassStudent = new student[(*m) * sizeof(student)];
    if (*noPassStudent == NULL) return -1;

    for (int i = 0;i < *m;i++)  *(*noPassStudent + i) = stu[a[i]];

    return 0;
}
int Pass(student stu[], int n, student** PassStudent, int* m)
{
    if (n <= 0 || stu == NULL)  return -1;

    *m = 0;
    int *a = new int[n*sizeof(int)];
    for (int i = 0;i < n;i++)
    {
        if (stu[i].sum >= 180)
        {
            a[*m] = i;
            *m += 1;
        }
    }
    *PassStudent = new student[(*m) * sizeof(student)];
    if (*PassStudent == NULL)
    {
        return -1;
    }
    for (int i = 0;i < *m;i++)
    {
        *(*PassStudent + i) = stu[a[i]];
    }
    return 0;
}

int SortStudents(student stu[], int n)
{
    if (n <= 0||stu==NULL)  return -1;

    for(int i = 0;i < n-1;i++){
        for(int j = i+1; j < n;j++){
            if(stu[j].sum > stu[i].sum) std::swap(stu[j],stu[i]);
        }
    }
    return 0;
}

int SearchStudent(student stu[], int n, int id, int* rank, student* rstu)
{
    int num = 0, y = 0;
    if (n <= 0||stu==NULL)
    {
        return -1;
    }
    for (int i = 0;i < n;i++)
    {
        if (id == stu[i].id)
        {

            *rstu = stu[i];
            num++;
            for (int s = 0;s < i;s++)
            {
                if (rstu->sum == stu[s].sum)
                {
                    y++;
                }
            }
            *rank = i + 1 - y;
            break;
        }
    }
    if (num == 0)
    {
        return -1;
    }
    return 0;
}
